package priv.wjh.study.easyexcel.multisheet;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
// 创建一个示例数据类


public class MultiSheetExportExample {

    public static void main(String[] args) throws IOException {
        Map<String, Boolean> mergedRegionMap = new ConcurrentHashMap<>();
        Consumer<Sheet> consumer = sheet -> {
            if (mergedRegionMap.containsKey(sheet.getSheetName())) {
                return;
            }
            CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0,
                                                                     2);
            sheet.addMergedRegion(cellRangeAddress);
            mergedRegionMap.put(sheet.getSheetName(), true);
        };

        // 创建ExcelWriter对象
        ExcelWriter excelWriter = EasyExcel.write("multi_sheet.xlsx").build();

        // 创建Sheet1数据
        List<Data> sheet1Data = new ArrayList<>();
        sheet1Data.add(new Data("Alice", 25));
        sheet1Data.add(new Data("Bob", 30));

        // 创建Sheet2数据
        List<Data> sheet2Data = new ArrayList<>();
        sheet2Data.add(new Data("Charlie", 28));
        sheet2Data.add(new Data("Diana", 22));

        // 写入Sheet1
        WriteSheet sheet1 = EasyExcel.writerSheet(0, "Sheet1")
                .registerWriteHandler(new MergeStrategy(consumer)).build();
        // 写入固定内容
        List<List<String>> data = new ArrayList<>();
        data.add(Arrays.asList("这是第一行固定内容"));
        data.add(Arrays.asList("标题1", "标题2", "标题3")); // 标题行
        // 写入数据内容（示例数据）
        data.add(Arrays.asList("数据1", "数据2", "数据3"));
        data.add(Arrays.asList("数据4", "数据5", "数据6"));
        // 可以添加更多的数据行...

        excelWriter.write(data, sheet1);
        excelWriter.write(sheet1Data, sheet1);

        // 写入Sheet2
        WriteSheet sheet2 = EasyExcel.writerSheet(1, "Sheet2").head(Data.class).build();
        excelWriter.write(sheet2Data, sheet2);

        // 关闭ExcelWriter，释放资源
        excelWriter.finish();
    }



}
